#财务支出类型数据统计服务类  flydragon
class StatisticalDatum::FinanceExpenditureTypeService
  include HeiPisService

  #company 单位
  def initialize(company)
    @company = company
  end


  #执行方法 返回值
  def call

    #=======最近30天数据=======#
    #时间数组
    expenditure_type_infos = {}

    # 产品支出(导师,产品总监,运营总监,前台)
    # 管理成本(固定成本,管理人员(主理人,财务人员,人资人员))
    # 营销成本 (市场专员,市场总监)
    # 学员退费
    # 其他支出(自定义职务)
    expenditure_types = %w(产品支出 营销支出 管理支出 学员退费 其他支出)

    expenditure_types.each{|type|
      expenditure_type_infos[type] = {:value => 0, name: type}
    }

    start_date = Date.new(Date.current.year, 1)
    end_date = Time.now

    # if @company.created_at.to_datetime > start_date
    #   start_date = @company.created_at.to_datetime
    # end

    finance_amount_by_category = lambda { |category|  
       sum = Finance.where({:company_id => @company.id,:finance_type => '支出',:finance_category => category,is_system: 0,:setdate => start_date..end_date}).sum(:amount)
       (sum||=0).round(2)
    }


    expenditure_type_infos["产品支出"][:value] = positons_salary_amount(%w(导师 产品总监 运营总监 前台),start_date,end_date)+finance_amount_by_category.call("产品成本")
    expenditure_type_infos["营销支出"][:value]  = positons_salary_amount(%w(市场总监 市场专员),start_date,end_date)+finance_amount_by_category.call("营销成本")
    expenditure_type_infos["管理支出"][:value]  = get_guanli_amount(start_date,end_date)+finance_amount_by_category.call("管理成本")
    expenditure_type_infos["学员退费"][:value]  = finance_amount_by_category.call("学员退费")
    expenditure_type_infos["其他支出"][:value]  = finance_amount_by_category.call("其他业务成本")


    expenditure_type_infos
  end

  # 计算职务的工资
  def positons_salary_amount(position_names,start_date,end_date)
    # 产品支出金额
    amount = 0

    sql = %Q{
      company_id = :company_id 
      and (month between :start_month and :end_month) 
      and position_names  REGEXP :position_name 
    }

    params = {:start_month => start_date.strftime("%Y-%m")}
    params[:end_month] = end_date.strftime("%Y-%m")
    params[:company_id] = @company.id

    position_names.each do |position_name|
      params[:position_name] = position_name.to_s
      sum_salary = SalaryMonthStatistic.where(sql,params).sum(:sum_salary)
      amount += sum_salary||=0
    end

    amount.round(2)
  end


  # 管理成本 = (固定成本,管理人员(主理人,财务人员,人资人员))
  def get_guanli_amount(start_date,end_date)

    guanli_amount = 0
    
    # 固定支出
    # 每月的固定支出
    pre_month_amount = FixedCost.joins(:studios).where({"studios.company_id"=> @company.id}).sum("fixed_costs.amount/fixed_costs.cycle")
    guanli_amount += months_for_dates(start_date,end_date)*pre_month_amount
    
    guanli_amount += positons_salary_amount(%w(主理人 财务总监 会计/出纳 人资行政总监 HR/行政),start_date,end_date)

    guanli_amount.round(2)
  end






end
